//
//  MaskView+Error.swift
//  Asman
//
//  Created by 李旭峰 on 7/9/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import Foundation

fileprivate var cx_errorViewKey:Void?
fileprivate var cx_errorRetryActionKey:Void?
typealias RetryActionType = () -> ()
extension UIView {
    fileprivate var errorMaskView:CXEmptyView?{
        set{
            objc_setAssociatedObject(self, &cx_errorViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &cx_errorViewKey) as? CXEmptyView
        }
    }
    fileprivate var retryAction:RetryActionType? {
        set{
            objc_setAssociatedObject(self, &cx_errorRetryActionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get{
            return objc_getAssociatedObject(self, &cx_errorRetryActionKey) as? RetryActionType
        }
    }
    func cx_showError(withAction action:RetryActionType?){
        if self.errorMaskView != nil {
            self.errorMaskView?.removeFromSuperview()
            self.errorMaskView = nil
        }
        self.retryAction = action
        self.errorMaskView = (Bundle.main.loadNibNamed("CXEmptyView", owner: nil, options: nil)?.first as? CXEmptyView)!
        self.errorMaskView?.imgEmptyLogo.image = UIImage(named: "img_empty_NoNetwork")
        self.errorMaskView?.lbContent.text = "出了一点小问题，请点击重试"
        self.errorMaskView?.btnAction.setTitle("点击重试", for: .normal)
        self.errorMaskView?.btnAction.isHidden = false
        self.errorMaskView?.btnAction.addTarget(self, action: #selector(onClickedRetryButton), for: .touchUpInside)
        self.addSubview(self.errorMaskView!)
        self.errorMaskView?.snp.remakeConstraints({ (make) in
            make.centerX.width.equalToSuperview()
            make.top.height.equalToSuperview()
        })
    }
    func cx_removeError(){
        if self.errorMaskView != nil {
            self.errorMaskView?.removeFromSuperview()
            self.errorMaskView = nil
        }
    }
    @objc func onClickedRetryButton(){
        if let retryAction = self.retryAction {
            retryAction()
        }
    }
}
